﻿using System;
using System.Management;
using System.Net.NetworkInformation;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;

namespace Launcher
{
    public static class SysInfo
    {
        #region Methods

        static bool AtLeastVista()
        {
            return (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6);
        }

        static string programFilesx86()
        {
            if (8 == IntPtr.Size
                || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
            {
                return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
            }

            return Environment.GetEnvironmentVariable("ProgramFiles");
        }

        //-------------------------------обьем ОЗУ в мегабайтах------------------ 

        static Int64 memory_size()
        {
            Int64 mem = 0;

            string s;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                      "SELECT * FROM Win32_ComputerSystem");//запрос WMI

            foreach (ManagementObject queryObj in searcher.Get())
            {
                s = queryObj["TotalPhysicalMemory"].ToString();//ищем сколько физической памяти на данном ПК
                mem = Int64.Parse(s) / 1048576;//переводим в мегабайты
            }

            return mem;
        }
        //--------------------------------------------------------------------

        [DllImport("user32.dll")]
        static extern UInt32 SendMessage(IntPtr hWnd, UInt32 msg, UInt32 wParam, UInt32 lParam);

        internal const int BCM_FIRST = 0x1600; //Normal button

        internal const int BCM_SETSHIELD = (BCM_FIRST + 0x000C); //Elevated button

        static  bool Admin()
        {
            WindowsIdentity id = WindowsIdentity.GetCurrent();
            WindowsPrincipal p = new WindowsPrincipal(id);
            return p.IsInRole(WindowsBuiltInRole.Administrator);
        }

        private static string getdomain()
        {
            string result = "";
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                    "SELECT * FROM Win32_ComputerSystem");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    result = queryObj["Domain"].ToString();
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
            return result;
        }

        static Mutex mutex; // семафор

        #endregion

        /// <summary>
        /// Местоположение папки Program Files (x86)
        /// </summary>
        /// <value>
        /// Возвращает  путь к папке Program Files 
        /// или Program Files (x86) для Windows x64
        /// </value>
        public static string ProgramFilesX86 { get { return programFilesx86(); } }

        public static bool IsVistaOrSeven { get { return AtLeastVista(); } }
        /// <summary>
        /// Размер ОЗУ в МБ
        /// </summary>
        /// <value>Возвращает размер ОЗУ в МБ</value>
        public static Int64 TotalPhysicalMemory { get { return memory_size(); } }
        /// <summary>
        /// Является ли пользователь администратором
        /// </summary>
        /// <value>
        /// Возвращает принадлежность пользователя к группе администраторов
        /// true-принадлежит
        /// false-не принадлежит
        /// </value>
        public static bool IsAdmin { get { return Admin(); } }
        
        /// <summary>
        /// Текущий домен
        /// </summary>
        /// <value>string Возвращает текущий домен</value>
        public static string CurrentDomain { get { return getdomain(); } }

        public static bool Already_Started(string MutexName)
        {
            bool createdNew;
            mutex = new Mutex(false, MutexName, out createdNew);//проверка наличия семафора виртуалфи в памяти            
            return !createdNew;
        }

        
        public static bool Ping(string Host)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.
            options.DontFragment = true;

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 50;
            try
            {
                PingReply reply = pingSender.Send(Host, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
            }
            catch
            {

                return false;
            }
            
            return false;
        }


    }
}
